package Solutions;

/***
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 *
 * 如果不存在公共前缀，返回空字符串 ""。
 *
 * 示例 1:
 *
 * 输入: ["flower","flow","flight"]
 * 输出: "fl"
 *
 * 示例 2:
 *
 * 输入: ["dog","racecar","car"]
 * 输出: ""
 * 解释: 输入不存在公共前缀。
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/longest-common-prefix
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class LongestCommonPrefix {

    public String longestCommonPrefix(String[] strings) {
        if (strings == null || strings.length == 0) return "";
        if (strings.length == 1) return strings[0];
        StringBuilder res = new StringBuilder();
        int minLength = strings[0].length();
        char tmp;
        for (String string : strings) {
            minLength = Math.min(minLength, string.length());
        }
        for (int i = 0; i < minLength; i++) {
            tmp = !strings[0].equals("") ? strings[0].charAt(i) : '-';
            for (int j = 1; j < strings.length; j++) {
                if (tmp != strings[j].charAt(i)) {
                    return res.toString();
                }
            }
            res.append(tmp);
        }
        return res.toString();
    }

    public static void main(String[] args) {
        String[] strings = new String[]{"bc", "b"};
        System.out.println(new LongestCommonPrefix().longestCommonPrefix(strings));
    }
}
